﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using YougeBookmark.Models;
using YougeBookmark.Services;
using YougeBookmark.Utilities;

namespace YougeBookmark.Views
{
    /// <summary>
    /// 主操作窗体（核心用户界面）
    /// </summary>
    public partial class MainForm : Form
    {
        private readonly DatabaseService _dbService = new DatabaseService();
        private List<Tag> _allTags = new List<Tag>();
        private PaginationHelper _pagination = new PaginationHelper();

        // UI控件
        private TextBox txtUrl;
        private CheckedListBox chkTags;
        private TextBox txtRemark;
        private Button btnSave;
        private Button btnQuery;
        private Button btnManageTags;
        private Button btnRemoveMenu;
        private DataGridView dgvResults;
        private DateTimePicker dtpStart;
        private Label lblUrl;
        private Label lblTags;
        private Label lblRemark;
        private Label lblDateRange;
        private Label lblTo;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
        private DateTimePicker dtpEnd;

        public MainForm()
        {
            InitializeComponent();
            Load += MainForm_Load;
        }

        /// <summary>
        /// 初始化窗体控件（替代设计器生成的代码）
        /// </summary>
        private void InitializeComponent()
        {
            lblUrl = new Label();
            txtUrl = new TextBox();
            lblTags = new Label();
            chkTags = new CheckedListBox();
            lblRemark = new Label();
            txtRemark = new TextBox();
            btnSave = new Button();
            btnQuery = new Button();
            btnManageTags = new Button();
            btnRemoveMenu = new Button();
            lblDateRange = new Label();
            dtpStart = new DateTimePicker();
            lblTo = new Label();
            dtpEnd = new DateTimePicker();
            dgvResults = new DataGridView();
            dataGridViewTextBoxColumn1 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn2 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn3 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn4 = new DataGridViewTextBoxColumn();
            ((System.ComponentModel.ISupportInitialize)dgvResults).BeginInit();
            SuspendLayout();
            // 
            // lblUrl
            // 
            lblUrl.Location = new Point(0, 0);
            lblUrl.Name = "lblUrl";
            lblUrl.Size = new Size(100, 23);
            lblUrl.TabIndex = 0;
            // 
            // txtUrl
            // 
            txtUrl.Location = new Point(0, 0);
            txtUrl.Name = "txtUrl";
            txtUrl.Size = new Size(100, 23);
            txtUrl.TabIndex = 1;
            // 
            // lblTags
            // 
            lblTags.Location = new Point(0, 0);
            lblTags.Name = "lblTags";
            lblTags.Size = new Size(100, 23);
            lblTags.TabIndex = 2;
            // 
            // chkTags
            // 
            chkTags.Location = new Point(0, 0);
            chkTags.Name = "chkTags";
            chkTags.Size = new Size(120, 94);
            chkTags.TabIndex = 3;
            // 
            // lblRemark
            // 
            lblRemark.Location = new Point(0, 0);
            lblRemark.Name = "lblRemark";
            lblRemark.Size = new Size(100, 23);
            lblRemark.TabIndex = 4;
            // 
            // txtRemark
            // 
            txtRemark.Location = new Point(0, 0);
            txtRemark.Name = "txtRemark";
            txtRemark.Size = new Size(100, 23);
            txtRemark.TabIndex = 5;
            // 
            // btnSave
            // 
            btnSave.Location = new Point(0, 0);
            btnSave.Name = "btnSave";
            btnSave.Size = new Size(75, 23);
            btnSave.TabIndex = 6;
            btnSave.Click += BtnSave_Click;
            // 
            // btnQuery
            // 
            btnQuery.Location = new Point(0, 0);
            btnQuery.Name = "btnQuery";
            btnQuery.Size = new Size(75, 23);
            btnQuery.TabIndex = 7;
            btnQuery.Click += BtnQuery_Click;
            // 
            // btnManageTags
            // 
            btnManageTags.Location = new Point(0, 0);
            btnManageTags.Name = "btnManageTags";
            btnManageTags.Size = new Size(75, 23);
            btnManageTags.TabIndex = 8;
            btnManageTags.Click += BtnManageTags_Click;
            // 
            // btnRemoveMenu
            // 
            btnRemoveMenu.Location = new Point(0, 0);
            btnRemoveMenu.Name = "btnRemoveMenu";
            btnRemoveMenu.Size = new Size(75, 23);
            btnRemoveMenu.TabIndex = 9;
            btnRemoveMenu.Click += BtnRemoveMenu_Click;
            // 
            // lblDateRange
            // 
            lblDateRange.Location = new Point(0, 0);
            lblDateRange.Name = "lblDateRange";
            lblDateRange.Size = new Size(100, 23);
            lblDateRange.TabIndex = 10;
            // 
            // dtpStart
            // 
            dtpStart.Location = new Point(0, 0);
            dtpStart.Name = "dtpStart";
            dtpStart.Size = new Size(200, 23);
            dtpStart.TabIndex = 11;
            // 
            // lblTo
            // 
            lblTo.Location = new Point(0, 0);
            lblTo.Name = "lblTo";
            lblTo.Size = new Size(100, 23);
            lblTo.TabIndex = 12;
            // 
            // dtpEnd
            // 
            dtpEnd.Location = new Point(0, 0);
            dtpEnd.Name = "dtpEnd";
            dtpEnd.Size = new Size(200, 23);
            dtpEnd.TabIndex = 13;
            // 
            // dgvResults
            // 
            dgvResults.Columns.AddRange(new DataGridViewColumn[] { dataGridViewTextBoxColumn1, dataGridViewTextBoxColumn2, dataGridViewTextBoxColumn3, dataGridViewTextBoxColumn4 });
            dgvResults.Location = new Point(0, 0);
            dgvResults.Name = "dgvResults";
            dgvResults.Size = new Size(597, 150);
            dgvResults.TabIndex = 14;
            // 
            // dataGridViewTextBoxColumn1
            // 
            dataGridViewTextBoxColumn1.HeaderText = "标签";
            dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
            // 
            // dataGridViewTextBoxColumn2
            // 
            dataGridViewTextBoxColumn2.HeaderText = "备注";
            dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
            // 
            // dataGridViewTextBoxColumn3
            // 
            dataGridViewTextBoxColumn3.HeaderText = "URL";
            dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
            // 
            // dataGridViewTextBoxColumn4
            // 
            dataGridViewTextBoxColumn4.HeaderText = "创建时间";
            dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
            // 
            // MainForm
            // 
            ClientSize = new Size(784, 561);
            Controls.Add(lblUrl);
            Controls.Add(txtUrl);
            Controls.Add(lblTags);
            Controls.Add(chkTags);
            Controls.Add(lblRemark);
            Controls.Add(txtRemark);
            Controls.Add(btnSave);
            Controls.Add(btnQuery);
            Controls.Add(btnManageTags);
            Controls.Add(btnRemoveMenu);
            Controls.Add(lblDateRange);
            Controls.Add(dtpStart);
            Controls.Add(lblTo);
            Controls.Add(dtpEnd);
            Controls.Add(dgvResults);
            Name = "MainForm";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "优哥书签 v1.0";
            Load += MainForm_Load_1;
            ((System.ComponentModel.ISupportInitialize)dgvResults).EndInit();
            ResumeLayout(false);
            PerformLayout();
        }

        /// <summary>
        /// 窗体加载初始化
        /// </summary>
        private async void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                _allTags = await _dbService.GetAllTagsAsync();
                chkTags.Items.Clear();
                foreach (var tag in _allTags)
                {
                    chkTags.Items.Add(tag.Name, false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        private async void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                var selectedIndices = chkTags.CheckedIndices;
                var tagIds = new List<int>();
                foreach (int index in selectedIndices)
                {
                    tagIds.Add(_allTags[index].Id);
                }

                var bookmark = new Bookmark
                {
                    Url = txtUrl.Text,
                    Remark = txtRemark.Text
                };

                var success = await _dbService.AddBookmarkAsync(bookmark, tagIds);
                if (success)
                {
                    MessageBox.Show("保存成功");
                    txtUrl.Clear();
                    txtRemark.Clear();
                    chkTags.ClearSelected();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 查询按钮点击事件
        /// </summary>
        private async void BtnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                // 设置查询条件
                _pagination.SetDateRange(dtpStart.Value, dtpEnd.Value);
                var selectedIndices = chkTags.CheckedIndices;
                var tagIds = new List<int>();
                foreach (int index in selectedIndices)
                {
                    tagIds.Add(_allTags[index].Id);
                }
                _pagination.AddTags(tagIds);

                // 执行查询
                var (data, total) = await _dbService.QueryBookmarksAsync(_pagination);
                dgvResults.Rows.Clear();
                foreach (var item in data)
                {
                    dgvResults.Rows.Add(
                        string.Join(", ", item.BookmarkTags.Select(bt => bt.Tag.Name)),
                        item.Remark,
                        item.Url,
                        item.CreatedTime.ToLocalTime()
                    );
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 管理标签按钮点击事件
        /// </summary>
        private void BtnManageTags_Click(object sender, EventArgs e)
        {
            var tagForm = new TagManagerForm(_dbService);
            if (tagForm.ShowDialog() == DialogResult.OK)
            {
                // 刷新标签列表
                MainForm_Load(null, null);
            }
        }

        /// <summary>
        /// 移除右键菜单按钮点击事件
        /// </summary>
        private void BtnRemoveMenu_Click(object sender, EventArgs e)
        {
            var result = RegistryHelper.UninstallContextMenu();
            MessageBox.Show(result ? "右键菜单已移除" : "移除失败，请检查权限");
        }

        /// <summary>
        /// 从剪贴板粘贴URL
        /// </summary>
        public void PasteUrlFromClipboard()
        {
            var (success, url) = ClipboardService.TryGetUrl();
            if (success)
            {
                txtUrl.Text = url;
            }
            else
            {
                MessageBox.Show("剪贴板中没有有效的URL");
            }
        }

        private void MainForm_Load_1(object sender, EventArgs e)
        {

        }
    }
}